/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.bean.listener;

import javax.ejb.Stateless;
import org.ipti.br.tag.bean.SessionBean;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 *
 * @author israel
 */

@Stateless
public class AuthorizationListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
        SessionBean sessionBean = context.getApplication().evaluateExpressionGet(context, "#{sessionBean}", SessionBean.class);
        String view = context.getViewRoot().getViewId();
        if((view).equals("/login/login.xhtml") || (view).equals("/educational/registration/humanRegister.xhtml") || (view).equals("/educational/main.xhtml") || (view).equals("/educational/synchronization/synchronization.xhtml")) {
            if(sessionBean.isLogged()) {
                NavigationHandler handler = context.getApplication().getNavigationHandler();
                handler.handleNavigation(context, null, "/educational/home/home?faces-redirect=true");
                context.renderResponse();
            }
        } else {            
            if(!sessionBean.isLogged()) {
                NavigationHandler handler = context.getApplication().getNavigationHandler();
                handler.handleNavigation(context, null, "/login/login?faces-redirect=true");
                context.renderResponse();
            }
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
    
}
